package com.heba.greenmulu.login;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.heba.ATApp;
import com.heba.AppManager;
import com.heba.Cfg;
import com.heba.Debug;
import com.heba.config.CommonConfig;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.MainActivity;
import com.heba.greenmulu.R;
import com.heba.helper.MemberShipHelper;
import com.heba.utils.CommonUtils;
import com.heba.utils.DensityUtils;
import com.heba.utils.StatusBarUtils;
import com.heba.utils.ToastShow;
import com.tencent.mm.opensdk.modelmsg.SendAuth;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;

/**
 * 注册页面
 * Created by jason on 2019/2/12.
 */

public class SignUpActivity extends BaseActivity implements View.OnClickListener {

    private ConstraintLayout topbar;
    private EditText edit_email;
    private EditText edit_password;
    private EditText edit_repassword;
    private Button btn_signup;
    private ImageView img_wechat;
    private ImageView img_facebook;

    private CallbackManager callbackManager;
    public static SignUpActivity instance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置状态栏透明
        StatusBarUtils.setStatusBar(this);
        setContentView(R.layout.activity_sign_up);
        instance = this;
        callbackManager = CallbackManager.Factory.create();
        initTopbar();
        findViewById();
        setTopbarPadding();
        initView();
        facebookLoginManager();
    }

    @Override
    protected void findViewById() {
        topbar = findViewById(R.id.topbar);
        edit_email = findViewById(R.id.edit_email);
        edit_password = findViewById(R.id.edit_password);
        edit_repassword = findViewById(R.id.edit_repassword);
        btn_signup = findViewById(R.id.btn_signup);
        img_wechat = findViewById(R.id.img_wechat);
        img_facebook = findViewById(R.id.img_facebook);

        img_wechat.setOnClickListener(this);
        img_facebook.setOnClickListener(this);
        btn_signup.setOnClickListener(this);
        btn_signup.setForceDarkAllowed(false);

    }

    @Override
    protected void initView() {
        txt_title.setText(getResources().getString(R.string.signup));
    }

    /**
     * Let topbar to extend to status bar.
     *
     * @notice this method have to be used after setContentView.
     */
    private void setTopbarPadding() {
        // Set the padding to match the Status Bar height
        topbar.setPadding(0, StatusBarUtils.getStatusBarHeight(this), 0, 0);
    }

    /**
     * Email登录
     */
    private void signupWithEmail() {
        DensityUtils.hideSoftWindow(this, edit_email);

        if (edit_email.getText().toString().trim().isEmpty() || edit_password.getText().toString().trim().isEmpty() ||
                edit_repassword.getText().toString().trim().isEmpty()) {
            ToastShow.displayToast(this, getResources().getString(R.string.sign_up_message_tips));
            return;
        }

        if (!CommonUtils.isEmail(edit_email.getText().toString())) {
            ToastShow.displayToast(this, getResources().getString(R.string.input_email_format));
            return;
        }

        if (!edit_password.getText().toString().trim().equals(edit_repassword.getText().toString().trim())) {
            ToastShow.displayToast(this, getResources().getString(R.string.please_input_same_password));
            return;
        }

        Bundle bundle = new Bundle();
        bundle.putString(CommonConfig.SIGNUP_TITLE, getResources().getString(R.string.sign_up_with_email));
        bundle.putString(CommonConfig.SIGNUP_EMAIL, edit_email.getText().toString());
        bundle.putString(CommonConfig.SIGNUP_PASSWORD, edit_password.getText().toString());
        openActivity(SignUpCompleteActivity.class, bundle);

//        loading.Start();
//        new MemberShipHelper(new MemberShipHelper.MembershipListener() {
//            @Override
//            public void Success() {
//                loading.End();
//                //如果用户没有完善信息，则跳转到完善信息界面
//                if (Cfg.LastName.isEmpty() || Cfg.BirthYear.isEmpty()) {
//                    Bundle bundle = new Bundle();
//                    bundle.putString(CommonData.SIGNUP_TITLE, getResources().getString(R.string.sign_up_with_email));
//                    openActivity(SignUpCompleteActivity.class, bundle);
//                } else {
//                    //用户已完善信息则跳转到首页
//                    AppManager.getAppManager().finishAllActivity();
//                    openActivity(MainActivity.class);
//                    ToastShow.displayToast(SignUpActivity.this, getResources().getString(R.string.login_success));
//                }
//            }
//
//            @Override
//            public void Fail(String error) {
//                loading.End();
//            }
//        }).emailSignup(this, edit_email.getText().toString(), edit_password.getText().toString());
    }

    /**
     * facebook登录回调
     */
    private void facebookLoginManager() {
        LoginManager.getInstance().registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        Debug.Log("facebook success", "loginResult");

                        /**
                         * 获取用户信息
                         */
                        AccessToken token = loginResult.getAccessToken();
                        GraphRequest request = GraphRequest.newMeRequest(token, new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {
                                Debug.Log("Facebook UserInfo:", response.toString());
                                try {
                                    String id = object.getString("id");
                                    String name = object.getString("name");
                                    String first_name = object.getString("first_name");
                                    String last_name = object.getString("last_name");
                                    String url = "";
//                                    String email = object.getString("email");
//                                    String birthday = object.getString("birthday");

                                    if (Profile.getCurrentProfile().getProfilePictureUri(200, 200) != null) {
                                        url = Profile.getCurrentProfile().getProfilePictureUri(200, 200).toString();
                                    }

                                    Debug.Log("Facebook UserIcon:", url);

                                    /**
                                     * 发送用户信息至服务器
                                     */
                                    progressDialog.show();
                                    new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                                        @Override
                                        public void Success() {
                                            progressDialog.dismiss();
                                            //如果用户没有完善信息，则跳转到完善信息界面
                                            if (Cfg.LastName.isEmpty() || Cfg.BirthYear.isEmpty()) {
                                                Bundle bundle = new Bundle();
                                                bundle.putString(CommonConfig.SIGNUP_TITLE, getResources().getString(R.string.sign_up_with_facebook));
                                                bundle.putString(CommonConfig.SIGNUP_ICON, Cfg.Icon);
                                                bundle.putString(CommonConfig.SIGNUP_FIRSTNAME, first_name);
                                                bundle.putString(CommonConfig.SIGNUP_LASTNAME, last_name);
                                                openActivity(SignUpCompleteActivity.class, bundle);
                                            } else {
                                                //用户已完善信息则跳转到首页
                                                AppManager.getAppManager().finishAllActivity();
                                                openActivity(MainActivity.class);
                                                ToastShow.displayToast(SignUpActivity.this, getResources().getString(R.string.login_success));
                                            }
                                        }

                                        @Override
                                        public void Fail(String error) {
                                            ToastShow.displayToast(SignUpActivity.this, getResources().getString(R.string.login_failure));
                                            progressDialog.dismiss();
                                        }
                                    }).facebookLogin(SignUpActivity.this, id, name, url);

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        Bundle parameters = new Bundle();
                        parameters.putString("fields", "id,name,picture,first_name,last_name");
                        request.setParameters(parameters);
                        request.executeAsync();
                    }

                    @Override
                    public void onCancel() {
                        Debug.Log("facebook cancel", "facebook cancel by user");
                    }

                    @Override
                    public void onError(FacebookException exception) {
                        Debug.Log("facebook error", "exception = " + exception.getMessage());
                        if (exception instanceof FacebookAuthorizationException) {
                            if (AccessToken.getCurrentAccessToken() != null) {
                                LoginManager.getInstance().logOut();
                            }
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_wechat:
                if (!ATApp.api.isWXAppInstalled()) {
                    //引导用户去安装微信
                    ToastShow.displayToast(SignUpActivity.this, getResources().getString(R.string.wechat_install));
                    Uri uri = Uri.parse("market://details?id=com.tencent.mm");//id为包名
                    Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(it);
                    return;
                }
                //调起微信授权
                progressDialog.show();
                final SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                ATApp.api.sendReq(req);
                break;
            case R.id.img_facebook:
                LoginManager.getInstance().logInWithReadPermissions(SignUpActivity.this, Arrays.asList("public_profile"));
                break;
            case R.id.btn_signup:
                signupWithEmail();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        callbackManager.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        super.onResume();
        progressDialog.dismiss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (instance != null) {
            instance = null;
        }
    }
}
